package com.ilovepostcard.utils;

import java.util.Calendar;

/**
 * Server support （固定8位长度字符串，如：19800130）
 * 
 */
public class DateUtil {

    public static boolean isValidServerDate(String str) {
        return str != null && str.length() == 8;
    }

    /**
     * 19850602 -> 1985-06-02
     * 
     * @param serverDate
     * @return
     */
    public static String server2display(String serverDate) {
        if (isValidServerDate(serverDate)) {
            return serverDate.substring(0, 4) + "-" + serverDate.substring(4, 6) + "-" + serverDate.substring(6);
        }
        return "";
    }

    /**
     * 1985-06-02 -> 19850602
     * 
     * @param displayDate
     * @return
     */
    public static String display2server(String displayDate) {
        if (displayDate != null && displayDate.length() == 10)
            return displayDate.substring(0, 4) + displayDate.substring(5, 7) + displayDate.substring(8);
        return "";
    }
    
    /**
     * 1985-06-02 -> calendar
     * 
     * @param displayDate
     * @return
     */
    public static Calendar display2calendar(String displayDate) {
        if (displayDate != null && displayDate.length() == 10) {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.YEAR, Integer.parseInt(displayDate.substring(0, 4)));
            calendar.set(Calendar.MONTH, Integer.parseInt(displayDate.substring(5, 7)) - 1);
            calendar.set(Calendar.DATE, Integer.parseInt(displayDate.substring(8)));
            return calendar;
        }
        return Calendar.getInstance();
    }

    public static String date2display(int year, int month, int date) {
        return year + "-" + trimMin2Char(month + 1) + "-" + trimMin2Char(date);
    }

    private static String trimMin2Char(int value) {
        if (value >= 10)
            return value + "";
        return "0" + value;
    }
}
